package com.rock.platform.util;

import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.AlgorithmParameterSpec;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class TripleDES {
	private static byte[] m_bytKey = { -101, -75, 6, 61, -127, 48, 103, 85, 12,
			-81, 50, 11, -16, 40, -49, -28, -61, 0, -76, -75, -125, -86, -98,
			12 };
	private static byte[] m_bytIV = { -88, -99, -22, 93, 67, -110, 108, -105 };

	private static SecretKey genDESKey(byte[] key_byte) {
		SecretKey k = new SecretKeySpec(key_byte, "DESede");
		return k;
	}

	private static AlgorithmParameterSpec genDESIv(byte[] iv_byte) {
		AlgorithmParameterSpec iv = new IvParameterSpec(iv_byte);
		return iv;
	}

	private static byte[] desEncrypt(SecretKey key, AlgorithmParameterSpec iv,
			byte[] src) throws NoSuchAlgorithmException,
			NoSuchPaddingException, IllegalBlockSizeException,
			BadPaddingException, InvalidKeyException,
			InvalidAlgorithmParameterException {
		Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
		cipher.init(1, key, iv);

		return cipher.doFinal(src);
	}

	private static byte[] desDecrypt(SecretKey key, AlgorithmParameterSpec iv,
			byte[] crypt) throws IllegalBlockSizeException,
			BadPaddingException, NoSuchAlgorithmException,
			NoSuchPaddingException, InvalidKeyException,
			InvalidAlgorithmParameterException {
		Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
		cipher.init(2, key, iv);

		return cipher.doFinal(crypt);
	}

	public static String toCryptoString(String strText)
			throws InvalidKeyException, NoSuchAlgorithmException,
			NoSuchPaddingException, IllegalBlockSizeException,
			BadPaddingException, InvalidAlgorithmParameterException {
		byte[] bytCryptoData = desEncrypt(genDESKey(m_bytKey),
				genDESIv(m_bytIV), strText.getBytes());

		BASE64Encoder encoder = new BASE64Encoder();
		String strRes = encoder.encode(bytCryptoData);

		return strRes;
	}

	public static String fromCryptoString(String strCrypto) throws IOException,
			InvalidKeyException, IllegalBlockSizeException,
			BadPaddingException, NoSuchAlgorithmException,
			NoSuchPaddingException, InvalidAlgorithmParameterException {
		BASE64Decoder decoder = new BASE64Decoder();
		byte[] bytCryptoData = decoder.decodeBuffer(strCrypto);

		byte[] bytData = desDecrypt(genDESKey(m_bytKey), genDESIv(m_bytIV),
				bytCryptoData);

		String strRes = new String(bytData);

		return strRes;
	}
}
